#!/bin/bash

# 检查是否安装了必要的工具
check_tool_installed() {
  local tool=$1
  if ! command -v $tool &> /dev/null
  then
    echo "$tool could not be found, please install it."
    exit 1
  fi
}

# 检查git, maven, docker 是否安装
echo "Checking for required tools..."
check_tool_installed git
check_tool_installed mvn
check_tool_installed docker

# 获取当前项目的路径
PROJECT_PATH=$(pwd)
echo "Project path: $PROJECT_PATH"

# 拉取最新的代码
echo "Pulling the latest code..."
git pull

# 使用Maven编译打包项目
echo "Compiling and packaging with Maven..."
mvn clean install -DskipTests

# 进入lark-admin目录，使用Dockerfile生成镜像
echo "Building Docker image for lark-admin..."
cd "$PROJECT_PATH/lark-admin" || exit
docker build -t di-lark-admin:latest .

# 进入lark-ui目录，使用Dockerfile生成镜像
echo "Building Docker image for lark-ui..."
cd "$PROJECT_PATH/lark-ui" || exit
docker build -t di-lark-ui:latest .

# 检查是否有lark-admin 和lark-ui 容器，如果有，停止并删除
echo "Checking for existing containers and stopping/removing them if they exist..."
docker rm -f $(docker ps -aqf "name=di-lark-admin") 2>/dev/null
docker rm -f $(docker ps -aqf "name=di-lark-ui") 2>/dev/null

# 启动这两个容器
echo "Starting di-lark-admin container..."
docker run -d -it --restart=unless-stopped --net=host --name di-lark-admin di-lark-admin:latest

echo "Starting di-lark-ui container..."
docker run -d -it --restart=unless-stopped -p 80:80 --name di-lark-ui di-lark-ui:latest

echo "Script completed."
